package com.baseframe.tool.utils.data;

import com.baseframe.tool.entity.Aem;
import com.baseframe.tool.entity.Bem;
import com.baseframe.tool.result.R;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

public class BeanUtil{

    private static Wrapper wrapper;

    public static Wrapper getWrapper(){
        if (wrapper == null){
            synchronized (BeanUtil.class){
                wrapper = new WrapperHandler();
            }
        }
        return wrapper;
    }


    public static <T> Map<String,Object> toMap(T bean){
        Map<String,Object> beanMap = new  LinkedHashMap<String,Object>();

        Class<?> clazz = bean.getClass();
        Field[] allFields = getWrapper().getAllFields(clazz);

        for (Field field : allFields) {
            try {
                PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(),clazz);
                Object value = descriptor.getReadMethod().invoke(bean);
                beanMap.put(field.getName(),value);
            } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }



        return beanMap;
    }




    public static void main(String[] args) {
        Aem aem = new Aem();
        Bem bem = new Bem();

        aem.setName("张三");
        aem.setAge(17);
        Bem copied = copyProperties(aem, bem,"age");
        System.out.println(copied);
    }


    /**
     * 拷贝对象属性值
     * @param source 源对象
     * @param target 目标对象
     * @param attributes 需要排除的属性
     * @return 目标对象
     * @param <S> 源对象泛型
     * @param <T> 目标对象泛型
     */
    public static <S,T> T copyProperties(S source, T target, String... attributes){


        return getWrapper().wrap(source,target,attributes);
    }

    public static <S,T> T deepCopyProperties(S source, T target, String... attributes){

        return null;
    }

    public static String[] getALLPropertiesName(Class<?> clazz){

        Field[] allFields = getWrapper().getAllFields(clazz);

        String collect = Arrays.stream(allFields).map(Field::getName).collect(Collectors.joining(","));

        return collect.split(",");

    }






}
